package com.fulihui.information.core.oss;

import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.fulihui.information.common.config.AppConst;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.io.File;
import java.io.IOException;

/**
 * 阿里云组件操作
 * Created by LeeSon on 2016/12/25 0025.
 */
@Component
public class Aliyun {
    @Autowired
    private AppConst         appConst;

    private static OSSClient ossClient;

    @PostConstruct
    public void init() {
        ClientConfiguration conf = new ClientConfiguration();
        conf.setConnectionTimeout(5000);
        conf.setMaxErrorRetry(3);

        ossClient = new OSSClient("http://" + appConst.getOssEndpoint(), appConst.getOssKeyId(),
            appConst.getOssKeySeySecret(), conf);
    }

    public void upload(String fileName, String fileType, String filePath) throws IOException {
        PutObjectResult result;
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentType("image/" + fileType);
        result = ossClient.putObject(appConst.getOssBucket(), fileName, new File(filePath), objectMetadata);
        if (null != result && null != result.getCallbackResponseBody()) {
            result.getCallbackResponseBody().close();
        }
    }

    @PreDestroy
    public void destroy() {
        if (null != ossClient) {
            ossClient.shutdown();
        }
    }
}